package com.my.interview.nio_socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

public class NioServerSocket {


    public static void main(String[] args) {

        try{
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.socket().bind(new InetSocketAddress(8888));
            //设置为非阻塞模式
            ssc.configureBlocking(false);
            //为ssc注册选择器
            Selector selector = Selector.open();
            ssc.register(selector, SelectionKey.OP_ACCEPT);
            //创建新的处理器
            Handler handler = new Handler(1024);
            while (true){
                //等待请求，每次等待阻塞3s,查过3s后继续向下运行，如果传入0或者不传参将一直阻塞
                if(selector.select(3000) == 0){
                    System.out.println("等待请求超时.....");
                    continue;
                }
                System.out.println("请求处理中==========");
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                while (keyIterator.hasNext()){
                    SelectionKey key = keyIterator.next();
                    try{
                        //接收到链接请求时
                        if(key.isAcceptable()){
                            handler.handleAccept(key);
                        }
                        //读数据
                        if(key.isReadable()){
                            handler.handleRead(key);
                        }
                    }catch (IOException e){
                        keyIterator.remove();
                        continue;
                    }
                    //处理完后，从待处理的SelectionKey迭代器中一处当前所使用的key
                    keyIterator.remove();
                }
            }
        }catch (IOException e){

        }


    }


    private static class Handler{

        private int bufferSize;
        private String localCharset = "UTF-8";

        public Handler() {
        }

        public Handler(int bufferSize) {
            this.bufferSize = bufferSize;
        }

        public Handler(int bufferSize, String localCharset) {
            if(bufferSize > 0){
                this.bufferSize = bufferSize;
            }
            if(localCharset != null)
                this.localCharset = localCharset;
        }

        public Handler(String localCharset) {
            this.localCharset = localCharset;
        }

        public void handleAccept(SelectionKey key) throws IOException{

            SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
            sc.configureBlocking(false);
            sc.register(key.selector(),SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
        }

        public void handleRead(SelectionKey key) throws IOException{

            //获取channel
            SocketChannel sc = (SocketChannel) key.channel();

            ByteBuffer byteBuffer = (ByteBuffer) key.attachment();
            byteBuffer.clear();
            if(sc.read(byteBuffer) == -1){
                sc.close();
            }else{
                //将buffer转化为读状态
                byteBuffer.flip();
                String receivedString = Charset.forName(localCharset).newDecoder().decode(byteBuffer).toString();
                System.out.println("received data from client: " + receivedString);

                //返回数据给客户端
                String sendString = "received data :  " + receivedString;
                byteBuffer = ByteBuffer.wrap(sendString.getBytes(localCharset));
                sc.write(byteBuffer);
                //关闭socket
                sc.close();
            }
        }
    }
}
